package com.tj.jinzao.presenter;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;

import com.tj.jinzao.api.SubscriberCallBack;
import com.tj.jinzao.base.BasePresenter;
import com.tj.jinzao.callback.IMainView;
import com.tj.jinzao.common.Settings;
import com.tj.jinzao.manager.UserManager;
import com.tj.jinzao.model.Article;
import com.tj.jinzao.model.FamilyMember;
import com.tj.jinzao.model.ResultResponse;
import com.tj.jinzao.model.User;

import java.util.List;
import java.util.Locale;

/**
 * 日记，文章列表处理
 * Created by wjy 2018/12/10.
 */
public class MainPresenter extends BasePresenter<IMainView<List<Article>>> {

    public MainPresenter(IMainView<List<Article>> view) {
        super(view);
    }

    //个人资料
    public void getPersonData(long id) {
        addSubscription(mApiService.getUserInfo(id), new SubscriberCallBack<User>(mView.getContext()) {
            @Override
            protected void onSuccess(User list) {
                if (mView != null) mView.onUserInfoSuccess(list);
            }

            @Override
            protected void onFailure(ResultResponse response) {
                if (mView != null) mView.onUserInfoFailed(response);
            }

            @Override
            protected boolean isShowProgress() {
                return false;
            }

            @Override
            protected void onPageSuccess(int currentPage, int allPage, int allSize) {
                if (mView != null) mView.onUserInfoFailed(null);
            }
        });
    }

    public void getFamilyList() {
        long uId = UserManager.getInstance().getUser().getId();
        addSubscription(mApiService.getFamilyMemberList(uId), new SubscriberCallBack<List<FamilyMember>>(mView.getContext()) {
            @Override
            protected void onSuccess(List<FamilyMember> list) {
                if (mView != null) mView.getFamily(list);
            }

            @Override
            protected void onFailure(ResultResponse response) {
                if (mView != null) mView.onRequestError(response.getMessage());
            }

            @Override
            protected boolean isShowProgress() {
                return true;
            }
        });
    }

    public void addFamily(String name) {
        long uId = UserManager.getInstance().getUser().getId();
        addSubscription(mApiService.addFamilyMember(uId, name), new SubscriberCallBack<FamilyMember>(mView.getContext()) {
            @Override
            protected void onSuccess(FamilyMember familyMember) {
                if (mView != null) mView.addFamily(familyMember);
            }

            @Override
            protected void onFailure(ResultResponse response) {
                if (mView != null) mView.onRequestError(response.getMessage());
            }

            @Override
            protected boolean isShowProgress() {
                return true;
            }
        });
    }

    public static Geocoder sGeocoder;    //获取并解析位置用
    public static Context sContext;

    public void getCityByLocation(Context context) {
        sContext = context.getApplicationContext();
        sGeocoder = new Geocoder(context, Locale.getDefault());
        LocationManager locationManager;        //管理Location及其他信息
        String serviceName = Context.LOCATION_SERVICE;
        locationManager = (LocationManager) context.getSystemService(serviceName);
        //privider类型
        String provider = LocationManager.NETWORK_PROVIDER;
        //定位设置
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_LOW);//低精度
        criteria.setAltitudeRequired(false);//不要求海拔
        criteria.setBearingRequired(false);//不要求方位
        criteria.setCostAllowed(false);//不允许资费
        criteria.setPowerRequirement(Criteria.POWER_LOW);//低耗电

        Location location = null;
        if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED
                && ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            location = locationManager.getLastKnownLocation(provider);
            //获取位置需要访问Google提供的服务进行位置解析，比较耗时所以就放在task中，（其实在Android6.0及以下，可以直接放在主线程中执行，Android8.0必须放在Task中）
            new GetCityNameByGeocoder(context, sGeocoder).execute(location);
            //第一个参数提供的类型，第二个参数更新周期(毫秒)，第三个最小距离间隔500m
            locationManager.requestLocationUpdates(provider, 300000, 500, sLocationListener);
        } else {
            ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
        }
    }

    private final LocationListener sLocationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            //获取位置需要访问Google提供的服务进行位置解析，比较耗时所以就放在task中，（其实在Android6.0及以下，可以直接放在主线程中执行，Android8.0必须放在Task中）
            new GetCityNameByGeocoder(sContext, sGeocoder).execute(location);
        }

        @Override
        public void onStatusChanged(String s, int i, Bundle bundle) {

        }

        @Override
        public void onProviderEnabled(String s) {

        }

        @Override
        public void onProviderDisabled(String s) {

        }
    };

    public class GetCityNameByGeocoder extends AsyncTask<Location, Void, String> {
        private Context context;
        private Geocoder geocoder;
        private RecyclerView weatherrecycler;

        public GetCityNameByGeocoder(Context context, Geocoder geocoder) {
            this.context = context;
            this.geocoder = geocoder;
            this.weatherrecycler = weatherrecycler;
        }

        @Override
        protected String doInBackground(Location... locations) {
            return getCityName(locations[0]);
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            if (s != null) {//返回的城市不为空，执行请求天气Task
//                App.sCity = new City();
//                App.sCity.setName(s);
                if (mView != null) {
                    mView.onLocation(s);
                }
//                new GetWeatherInfoTask(context,weatherrecycler).execute(s);
            }
        }

        private String getCityName(Location location) {
            String tmpCity = "";
            double lat = 0;
            double lng = 0;
            List<Address> addressList = null;
            if (location != null) {
                lat = location.getLatitude();
                lng = location.getLongitude();
            } else {
                tmpCity = null;
            }
            try {
                //此处访问Google的位置服务，需要放在异步线程中
                addressList = geocoder.getFromLocation(lat, lng, 1);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (addressList != null && addressList.size() > 0) {
                Address address = addressList.get(0);
                //获取目标城市
                String subCity = address.getSubLocality();
                tmpCity = address.getLocality();
            }
            if (!TextUtils.isEmpty(tmpCity) && tmpCity.length() > 0) {
                tmpCity = tmpCity.substring(0, (tmpCity.length() - 1));
            }
            if(mView!=null){
                Settings.saveCity(mView.getContext(), tmpCity, lat, lng);
            }
            return tmpCity;
        }
    }
}
